package cn.quang.search.admin.entity.dto;

import cn.quang.search.common.utils.FastJsonUtils;
import lombok.Data;

@Data
public class Result<T> {

    /**
     * 操作成功
     */
    public final static int STATUS_OK = 200;

    /**
     * 操作警告
     */
    public final static int STATUS_WARNING = 300;

    /**
     * 操作失败
     */
    public final static int STATUS_FAILURE = 500;

    private int status;
    private String message;
    private T tag;

    public Result() {
        this.status = STATUS_OK;
        this.message = "执行成功";
    }

    public boolean isSuccess() {
        return status == STATUS_OK;
    }

    public boolean isWarning() {
        return status == STATUS_WARNING;
    }

    public boolean isFail() {
        return status != STATUS_OK;
    }

    public Result<T> changeErr(String message) {
        this.status = STATUS_FAILURE;
        this.message = message;
        return this;
    }

    public Result<T> changeErr(String message, T tag) {
        this.status = STATUS_FAILURE;
        this.message = message;
        this.tag = tag;
        return this;
    }

    public Result<T> changeSucc(T tag) {
        this.status = Result.STATUS_OK;
        this.tag = tag;
        return this;
    }

    public Result<T> changeWarn(String message){
        this.status = Result.STATUS_WARNING;
        this.message = message;
        return this;
    }

    public Result<T> changeWarn(String message, T tag){
        this.status = Result.STATUS_WARNING;
        this.message = message;
        this.tag = tag;
        return this;
    }

    public static final Result<?> SUCCESS = new Result<>(){
        @Override
        public boolean isFail() { return false; }
        @Override
        public boolean isSuccess() { return !isFail(); }
        @Override
        public boolean isWarning() { return false; }
    };

    @Override
    public String toString() {
        if (tag == null) {
            return String.format("status:%d, message:%s", status, message);
        } else {
            return String.format("status:%d, message:%s, tag:%s", status, message, FastJsonUtils.beanToJson(tag));
        }
    }
}
